﻿/*
Desc:进程内事件存储
Author:Joker
CreatedDate:24-02-02
*/

using ElectronicMall.Domain.Abstractions.Events;
using Microsoft.Extensions.Logging;

namespace ElectronicMall.Domain.Buses.MediatR.Events
{
    /// <summary>
    /// 进程内事件存储，只写入日志
    /// </summary>
    public class InProcessEventStore : IEventStore
    {
        protected readonly ILogger _logger;

        public InProcessEventStore(ILogger<InProcessEventStore> logger)
        {
            _logger = logger;
        }

        public void Save(IEvent @event)
        {
            SaveAsync(@event).Wait();
        }

        public Task SaveAsync(IEvent @event, CancellationToken cancellationToken = default)
        {
            _logger.LogInformation("{datetime} 发布了事件 {commandId}", @event.Timestamp, @event.Id);
            return Task.CompletedTask;
        }
    }


    /// <summary>
    /// 进程内事件存储，只写入日志
    /// </summary>
    /// <typeparam name="TResult">返回值类型</typeparam>
    public class InProcessEventStore<TResult> : InProcessEventStore, IEventStore<TResult>
    {
        public InProcessEventStore(ILogger<InProcessEventStore<TResult>> logger) : base(logger)
        {
        }

        TResult? IEventStore<TResult>.Save(IEvent @event)
        {
            Save(@event);
            return default;
        }

        async Task<TResult?> IEventStore<TResult>.SaveAsync(IEvent @event, CancellationToken cancellationToken)
        {
            await SaveAsync(@event, cancellationToken);
            return default(TResult);
        }
    }

}
